import { OrderItemModel } from "./declare"
import { observable, action } from "mobx"
import { getUserId, launchPay } from '@/utils/utils';
import { ORDER_STATUS, ORDER_TYPE, ORDER_TAB_STATUS, ORDER_STATUS_ARRAY } from '@/utils/constants';
import { network } from "@/utils/network"
import Taro from '@tarojs/taro'
import { cartModel } from "./CartModel";

/**
 * 订单model
 */
class OrderModel {

  @observable.ref
  items: OrderItemModel[]

  ORDER_STATUS: Object
  ORDER_TYPE: Object
  ORDER_TAB_STATUS: Object
  ORDER_STATUS_ARRAY: Array<string>
  order_type: string
  status: string

  @observable
  loading: boolean

  @observable.ref
  shopDetail: any

  hooks: Array<(cart: OrderItemModel) => void>

  constructor() {
    // 默认给4个 skeleton
    this.items = Array.from({ length: 4 });
    this.hooks = []
    this.ORDER_STATUS = ORDER_STATUS;
    this.ORDER_TYPE = ORDER_TYPE;
    this.ORDER_TAB_STATUS = ORDER_TAB_STATUS
    this.ORDER_STATUS_ARRAY = ORDER_STATUS_ARRAY
    this.order_type = 'all'
    this.status = '';
    this.loading = true;
    this.shopDetail = {}
  }

  @action
  total(items) {
    return items ? items.reduce((p, n) => p + n.number, 0) : 0;
  }

  @action
  setValue(list) {
    this.items = list
  }



  setOrderType(key) {
    this.order_type = key;
    this.getData();
  }

  setStatus(key) {
    this.status = key;
    this.getData();
  }

  async getData() {
    Taro.showLoading({ title: '加载中' })
    const params = {
      user_id: getUserId(),
      status: this.status
    }
    if (this.order_type !== 'all') {
      Object.assign(params, { order_type: this.order_type });
    }

    try {
      const { data } = await network.get('/xxm/order/list', params);
      this.setValue(data.list)
    } catch (error) {
    } finally {
      this.loading = false
      Taro.hideLoading()
    }

  }

  payById(order_id) {
    console.log('order_id', order_id);
    network.post('/xxm/order/pay/id', {
      user_id: getUserId(),
      order_id,
    }).then(res => {
      const { data: { appid, prepay_id } } = res;
      cartModel.clear()
      launchPay({ appid, prepay_id })
    })
  }


}

export const orderModel = new OrderModel()
